package com.etc.util;

import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Servlet implementation class DownloadFileServlet
 */
@WebServlet("/DownloadFile")
public class DownloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("进入文件下载");
		//读取服务器指定位置的文件,显示到界面上
		//存储头像文件的目录
		String root = "E:\\uploadFileImg\\";
		//获取指定文件名movieImg
		String fileName = request.getParameter("sightImg");
		//查找该文件s
		File file = new File(root+fileName);
		//通过文件字节流下载用户请求的文件，从服务器D盘位置读出来
		FileInputStream fis = new FileInputStream(file);
		//字节数组输出流
		ByteArrayOutputStream bos =  new ByteArrayOutputStream();
		
		byte[] bs = new byte[1024];
		int n;
		//读
		while ( ( n=fis.read(bs) ) != -1 ) {	
			//写
			bos.write(bs, 0, n);
		}
		fis.close();
		bos.close();
		
		//通过servlet输出流将文件以字节数组的形式输出到JSP界面中
		ServletOutputStream outs = response.getOutputStream();
		outs.write(bos.toByteArray());
		
		outs.flush();
		outs.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
